<template>
  <div class="profile-container">
    <!-- 顶部导航栏 -->
    <header class="profile-header">
      <button class="back-btn" @click="goBack">
        <span class="back-icon">‹</span>
        返回
      </button>
    </header>

    <!-- 个人信息区域 -->
    <main class="profile-main">
      <!-- 头像和姓名区域 -->
      <div class="profile-header-info">
        <h2 class="student-name" :class="{ 'loading-text': loading }">
          {{ loading ? '加载中...' : (studentInfo?.realName || '学生') }}
        </h2>
        <div class="avatar-placeholder">
          <span class="avatar-text">{{ avatarInitial }}</span>
        </div>
      </div>

      <!-- 基本信息卡片 -->
      <div class="info-card">
        <!-- 修改按钮 -->
        <button class="card-edit-btn" @click="editBasicInfo">✏️</button>
        <!-- 基本信息 -->
        <div class="info-item readonly">
          <span class="info-label">学 号：</span>
          <span class="info-value" :class="{ 'loading-text': loading }">
            {{ loading ? '加载中...' : (studentInfo?.studentId || '暂无') }}
          </span>
        </div>
        <div class="info-item">
          <span class="info-label">年 龄：</span>
          <span class="info-value" :class="{ 'loading-text': loading }">
            {{ loading ? '加载中...' : (studentInfo?.age || '暂无') }}
          </span>
        </div>
        <div class="info-item">
          <span class="info-label">手 机 号：</span>
          <span class="info-value" :class="{ 'loading-text': loading }">
            {{ loading ? '加载中...' : (studentInfo?.phone || '暂无') }}
          </span>
        </div>
        <div class="info-item">
          <span class="info-label">邮 箱：</span>
          <span class="info-value" :class="{ 'loading-text': loading }">
            {{ loading ? '加载中...' : (studentInfo?.email || '暂无') }}
          </span>
        </div>
        <div class="info-item">
          <span class="info-label">身份证号：</span>
          <span class="info-value" :class="{ 'loading-text': loading }">
            {{ loading ? '加载中...' : (studentInfo?.idCard || '暂无') }}
          </span>
        </div>

        <div class="info-item">
          <span class="info-label">学院：</span>
          <span class="info-value" :class="{ 'loading-text': loading }">
            {{ loading ? '加载中...' : (studentInfo?.college || '暂无') }}
          </span>
        </div>
      </div>



      <!-- 所在队伍信息 -->
      <div class="section-card">
        <h3 class="section-title">所在队伍：</h3>
        <div v-if="teamsLoading" class="loading-container">
          <div class="loading-text">加载中...</div>
        </div>
        <div v-else-if="studentTeams.length > 0" class="team-buttons">
          <button
            v-for="team in studentTeams"
            :key="team.teamId"
            class="team-btn"
            @click="goToTeamDetail(team)"
            :title="`队伍编号: ${team.teamCode}`"
          >
            {{ team.teamName }}
          </button>
        </div>
        <div v-else class="empty-teams">
          <div class="empty-text">暂无所在队伍</div>
          <div class="empty-hint">可以搜索并申请加入合适的队伍</div>
        </div>
      </div>

      <!-- 技能特长 -->
      <div class="section-card">
        <h3 class="section-title">技能特长：</h3>
        <div v-if="loading" class="loading-container">
          <div class="loading-text">加载中...</div>
        </div>
        <div v-else-if="studentSkills.length > 0" class="skills-display">
          <span
            v-for="skill in studentSkills"
            :key="skill.id"
            class="skill-tag"
          >
            {{ skill.skillName }}
          </span>
        </div>
        <div v-else class="empty-skills">
          <div class="empty-text">暂无技能特长信息</div>
          <div class="empty-hint">暂无技能特长信息</div>
        </div>
      </div>



      <!-- 获奖情况 -->
      <div class="section-card">
        <div class="section-header">
          <h3 class="section-title">获奖情况：</h3>
        </div>
        <StudentAwardsManager />
      </div>

      <!-- 参赛经历 -->
      <div class="section-card">
        <div class="section-header">
          <h3 class="section-title">参赛经历：</h3>
        </div>
        <StudentCompetitionsManager />
      </div>

      <!-- 项目经历 -->
      <div class="section-card">
        <div class="section-header">
          <h3 class="section-title">项目经历：</h3>
        </div>
        <StudentProjectsManager />
      </div>

      <!-- 教育背景 -->
      <div class="section-card">
        <div class="section-header">
          <h3 class="section-title">教育背景：</h3>
        </div>
        <StudentEducationManager />
      </div>

      <!-- 底部按钮 -->
      <div class="bottom-actions">
        <!-- <button class="qr-btn" @click="generateQR">生成页面二维码</button> -->
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </div>
    </main>

    <!-- 退出登录确认弹窗 -->
    <div v-if="showLogoutModal" class="modal-overlay" @click="closeLogoutModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>确认退出</h3>
          <button class="close-btn" @click="closeLogoutModal">×</button>
        </div>
        <div class="modal-body">
          <div class="icon-wrapper">
            <div class="warning-icon">⚠️</div>
          </div>
          <p class="modal-text">确定要退出登录吗？</p>
          <p class="modal-subtitle">退出后需要重新登录才能使用系统</p>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeLogoutModal">取消</button>
          <button class="confirm-btn" @click="confirmLogout">确认退出</button>
        </div>
      </div>
    </div>

    <!-- 基本信息编辑弹窗 -->
    <div v-if="showBasicInfoModal" class="modal-overlay" @click="closeBasicInfoModal">
      <div class="modal-content edit-modal" @click.stop>
        <div class="modal-header">
          <h3>编辑基本信息</h3>
          <button class="close-btn" @click="closeBasicInfoModal">×</button>
        </div>
        <div class="modal-body">
          <form class="edit-form">
            <div class="form-group">
              <label>年龄：</label>
              <input
                v-model="basicInfoForm.age"
                type="number"
                class="form-input"
                placeholder="请输入年龄"
                min="16"
                max="30"
              />
            </div>
            <div class="form-group">
              <label>手机号：</label>
              <input
                v-model="basicInfoForm.phone"
                type="tel"
                class="form-input"
                placeholder="请输入手机号"
                maxlength="11"
              />
            </div>
            <div class="form-group">
              <label>邮箱：</label>
              <input
                v-model="basicInfoForm.email"
                type="email"
                class="form-input"
                placeholder="请输入邮箱地址"
              />
            </div>
            <div class="form-group">
              <label>身份证号：</label>
              <input
                v-model="basicInfoForm.idCard"
                type="text"
                class="form-input"
                placeholder="请输入身份证号"
                maxlength="18"
              />
            </div>
            <div class="form-group">
              <label>学院：</label>
              <input
                v-model="basicInfoForm.college"
                type="text"
                class="form-input"
                placeholder="请输入学院"
              />
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeBasicInfoModal" :disabled="basicInfoLoading">取消</button>
          <button class="confirm-btn" @click="saveBasicInfo" :disabled="basicInfoLoading">
            {{ basicInfoLoading ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 消息提示弹窗 -->
    <div v-if="showMessageModal" class="modal-overlay" @click="closeMessageModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header" :class="messageType === 'success' ? 'success-header' : 'error-header'">
          <h3>{{ messageTitle }}</h3>
          <button class="close-btn" @click="closeMessageModal">×</button>
        </div>
        <div class="modal-body">
          <div class="icon-wrapper">
            <div class="message-icon" :class="messageType === 'success' ? 'success-icon' : 'error-icon'">
              {{ messageType === 'success' ? '✓' : '✗' }}
            </div>
          </div>
          <p class="modal-text">{{ messageText }}</p>
        </div>
        <div class="modal-footer">
          <button class="confirm-btn" @click="closeMessageModal">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { useStudentStore } from '@/stores/student.js'
import { getStudentInfoService, getStudentMyInfoService } from '@/api/student.js'
import StudentAwardsManager from '@/components/StudentAwardsManager.vue'
import StudentCompetitionsManager from '@/components/StudentCompetitionsManager.vue'
import StudentProjectsManager from '@/components/StudentProjectsManager.vue'
import StudentEducationManager from '@/components/StudentEducationManager.vue'

const router = useRouter()
const tokenStore = useTokenStore()
const studentStore = useStudentStore()

// 退出登录弹窗控制
const showLogoutModal = ref(false)
// 数据加载状态
const loading = ref(false)

// 基本信息编辑弹窗控制
const showBasicInfoModal = ref(false)
const basicInfoForm = ref({
  age: '',
  phone: '',
  email: '',
  idCard: '',
  college: ''
})
const basicInfoLoading = ref(false)

// 消息提示弹窗控制
const showMessageModal = ref(false)
const messageTitle = ref('')
const messageText = ref('')
const messageType = ref('success') // success | error

// 学生队伍信息
const studentTeams = ref([])
const teamsLoading = ref(false)
// 添加技能数据存储
const studentSkillsData = ref([])

// 获取学生信息
const studentInfo = computed(() => studentStore.studentInfo)

// 学生技能信息
const studentSkills = computed(() => {
  return studentSkillsData.value || []
})

// 头像首字母
const avatarInitial = computed(() => {
  if (loading.value) return '...'
  const name = studentInfo.value?.realName || '学生'
  return name.charAt(0)
})

// 页面挂载时获取学生信息
onMounted(async () => {
  // 检查登录状态
  if (!tokenStore.token) {
    router.push('/login')
    return
  }

  // 总是从服务器获取最新的学生信息
  await fetchStudentInfo()
  // 获取学生队伍信息
  await fetchStudentTeams()
})

// 获取学生信息
const fetchStudentInfo = async () => {
  loading.value = true
  try {
    const result = await getStudentInfoService()
    if (result.code === 200) {
      studentStore.setStudentInfo(result.data)
    } else {
      console.error('获取学生信息失败:', result.msg)
    }
  } catch (error) {
    console.error('获取学生信息异常:', error)
  } finally {
    loading.value = false
  }
}

// 获取学生综合信息（包括队伍和技能）
const fetchStudentMyInfo = async () => {
  teamsLoading.value = true
  try {
    console.log('开始获取学生综合信息...')
    const result = await getStudentMyInfoService()
    console.log('学生综合信息API响应:', result)
    
    if (result.code === 200) {
      const data = result.data
      
      // 更新队伍信息
      studentTeams.value = data.teams || []
      console.log('学生队伍信息加载成功:', studentTeams.value.length, '个队伍')
      
      // 更新技能信息  
      studentSkillsData.value = data.skills || []
      console.log('学生技能信息加载成功:', studentSkillsData.value.length, '项技能')
    } else {
      console.error('获取学生综合信息失败:', result.msg)
      showErrorMessage(result.msg || '获取学生综合信息失败')
      studentTeams.value = []
      studentSkillsData.value = []
    }
  } catch (error) {
    console.error('获取学生综合信息异常:', error)
    showErrorMessage('获取学生综合信息时发生错误')
    studentTeams.value = []
    studentSkillsData.value = []
  } finally {
    teamsLoading.value = false
  }
}

// 保留原有的fetchStudentTeams函数名，但调用新的综合信息接口
const fetchStudentTeams = async () => {
  await fetchStudentMyInfo()
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 编辑基本信息
const editBasicInfo = () => {
  // 预填充当前数据
  basicInfoForm.value = {
    age: studentInfo.value?.age || '',
    phone: studentInfo.value?.phone || '',
    email: studentInfo.value?.email || '',
    idCard: studentInfo.value?.idCard || '',
    college: studentInfo.value?.college || ''
  }
  showBasicInfoModal.value = true
}

// 关闭基本信息编辑弹窗
const closeBasicInfoModal = () => {
  showBasicInfoModal.value = false
  basicInfoForm.value = {
    age: '',
    phone: '',
    email: '',
    idCard: '',
    college: ''
  }
}

// 保存基本信息
const saveBasicInfo = async () => {
  basicInfoLoading.value = true
  try {
    // TODO: 调用更新学生基本信息的API
    // const result = await updateStudentBasicInfoService(basicInfoForm.value)
    // if (result.code === 200) {
    //   await fetchStudentInfo()
    //   closeBasicInfoModal()
    //   showSuccessMessage('基本信息更新成功')
    // } else {
    //   showErrorMessage(result.msg || '基本信息更新失败')
    // }

    // 暂时模拟成功
    setTimeout(() => {
      closeBasicInfoModal()
      showSuccessMessage('基本信息更新成功')
      basicInfoLoading.value = false
    }, 1000)
  } catch (error) {
    console.error('更新基本信息异常:', error)
    showErrorMessage('更新基本信息时发生错误')
    basicInfoLoading.value = false
  }
}

// 生成二维码
const generateQR = () => {
  console.log('生成页面二维码')
}

// 退出登录 - 显示确认弹窗
const handleLogout = () => {
  showLogoutModal.value = true
}

// 关闭退出登录弹窗
const closeLogoutModal = () => {
  showLogoutModal.value = false
}

// 确认退出登录
const confirmLogout = () => {
  tokenStore.removeToken()
  studentStore.removeStudentInfo()
  showLogoutModal.value = false
  router.push('/login')
}

// 显示成功消息
const showSuccessMessage = (text) => {
  messageTitle.value = '操作成功'
  messageText.value = text
  messageType.value = 'success'
  showMessageModal.value = true
}

// 显示错误消息
const showErrorMessage = (text) => {
  messageTitle.value = '操作失败'
  messageText.value = text
  messageType.value = 'error'
  showMessageModal.value = true
}

// 关闭消息弹窗
const closeMessageModal = () => {
  showMessageModal.value = false
}

// 跳转到队伍详情页面
const goToTeamDetail = (team) => {
  console.log('跳转到队伍详情:', team)
  
  const teamId = team.teamId
  
  if (!teamId) {
    showErrorMessage('队伍ID信息缺失')
    return
  }
  
  // 跳转到队伍详情页面
  router.push({
    name: 'TeamDetail',
    params: { teamId: teamId }
  })
}


</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #334cca 0%, #bcbceb 30%, #fdfdfd 60%, #ffffff 100%);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 顶部导航栏 */
.profile-header {
  padding: 15px 20px;
  background: transparent;
}

.back-btn {
  background: none;
  border: none;
  color: white;
  font-size: 18px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
}

.back-icon {
  font-size: 24px;
  font-weight: bold;
}

/* 主要内容区域 */
.profile-main {
  padding: 0 20px 40px;
  position: relative;
}

/* 头像和姓名区域 */
.profile-header-info {
  text-align: center;
  margin-bottom: 15px;
  position: relative;
}

/* 基本信息卡片 */
.info-card {
  background: white;
  border-radius: 15px;
  padding: 50px 25px 30px;
  margin-bottom: 20px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  position: relative;
}

/* 卡片右上角编辑按钮 */
.card-edit-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: background-color 0.2s;
  z-index: 5;
}

.card-edit-btn:hover {
  background: rgba(124, 77, 255, 0.1);
}

.avatar-placeholder {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(135deg, #7c4dff 0%, #8b5cf6 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(124, 77, 255, 0.3);
  position: absolute;
  top: 40px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
  border: 3px solid white;
}

.avatar-text {
  color: white;
  font-size: 32px;
  font-weight: bold;
}

.student-name {
  margin: 0 0 65px 0;
  font-size: 24px;
  font-weight: 600;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

/* 信息项 */
.info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 0;
  font-size: 18px;
  border-bottom: 1px solid #e5e7eb;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item.readonly {
  opacity: 0.6;
  background: rgba(0, 0, 0, 0.02);
}

.info-item.readonly .info-label,
.info-item.readonly .info-value {
  color: #666;
}

.info-label {
  color: #000;
  font-weight: 500;
  flex-shrink: 0;
}

.info-value {
  color: #000;
  text-align: right;
  word-break: break-all;
}

/* 加载状态样式 */
.loading-text {
  color: #999;
  font-style: italic;
  opacity: 0.8;
}



/* 各个信息区域卡片 */
.section-card {
  background: white;
  border-radius: 15px;
  padding: 20px 25px;
  margin-bottom: 20px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
}

.team-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.team-btn {
  padding: 8px 16px;
  background: #4285f4;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.team-btn:hover {
  background: #3367d6;
}

.empty-teams, .empty-skills {
  text-align: center;
  padding: 30px 20px;
}

.empty-text {
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.empty-hint {
  font-size: 14px;
  color: #999;
  line-height: 1.4;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80px;
  color: #666;
}

.skills-display {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.skill-tag {
  padding: 6px 12px;
  background: #4285f4;
  color: white;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
}

/* 底部按钮样式 */
.bottom-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin: 30px 0 20px;
  padding: 0 20px;
}

.qr-btn, .logout-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 120px;
}

.qr-btn {
  background: #4285f4;
  color: white;
}

.qr-btn:hover {
  background: #3367d6;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(66, 133, 244, 0.3);
}

.logout-btn {
  background: #dc3545;
  color: white;
}

.logout-btn:hover {
  background: #c82333;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3);
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.modal-content {
  background: white;
  border-radius: 16px;
  padding: 0;
  max-width: 480px;
  width: 90%;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  transform: scale(1);
  transition: all 0.3s ease;
}

.modal-content.edit-modal {
  max-width: 520px;
}

.modal-header {
  padding: 24px 28px 16px;
  text-align: center;
  position: relative;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  position: absolute;
  top: 20px;
  right: 24px;
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #666;
}

.modal-body {
  padding: 24px 28px;
  text-align: center;
}

.modal-body p {
  margin: 8px 0;
  color: #666;
  line-height: 1.6;
  font-size: 15px;
}

.modal-text {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.modal-subtitle {
  font-size: 14px;
  color: #999;
}

.icon-wrapper {
  margin-bottom: 16px;
}

.warning-icon {
  font-size: 48px;
  margin-bottom: 8px;
}

.message-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  font-weight: bold;
  margin: 0 auto 8px;
}

.success-icon {
  background: #d4edda;
  color: #155724;
}

.error-icon {
  background: #f8d7da;
  color: #721c24;
}

.success-header {
  border-bottom-color: #d4edda;
}

.error-header {
  border-bottom-color: #f8d7da;
}

.modal-footer {
  padding: 16px 28px 24px;
  text-align: center;
  display: flex;
  gap: 12px;
  justify-content: center;
}

/* 弹窗按钮样式 */
.cancel-btn, .confirm-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 100px;
}

.cancel-btn {
  background: #f8f9fa;
  color: #6c757d;
  border: 1px solid #dee2e6;
}

.cancel-btn:hover {
  background: #e9ecef;
  color: #495057;
  transform: translateY(-1px);
}

.confirm-btn {
  background: #4285f4;
  color: white;
}

.confirm-btn:hover {
  background: #3367d6;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(66, 133, 244, 0.3);
}

.confirm-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 编辑表单样式 */
.edit-form {
  text-align: left;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #4285f4;
  box-shadow: 0 0 0 3px rgba(66, 133, 244, 0.1);
}

.form-input::placeholder {
  color: #999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-main {
    padding: 0 15px 40px;
  }

  .bottom-actions {
    flex-direction: column;
    gap: 12px;
    padding: 0 15px;
  }

  .qr-btn, .logout-btn {
    width: 100%;
  }


  .modal-content {
    width: 95%;
    margin: 20px;
  }

  .modal-header {
    padding: 20px 20px 12px;
  }

  .modal-body {
    padding: 20px;
  }

  .modal-footer {
    padding: 12px 20px 20px;
    flex-direction: column;
    gap: 8px;
  }

  .cancel-btn, .confirm-btn {
    width: 100%;
  }
}
</style>

